package src.com.neusoft.nep.controller;

import src.com.neusoft.nep.common.AdAlertUtils;
import src.com.neusoft.nep.common.FileUtils;
import src.com.neusoft.nep.entity.FeedbackData;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.*;

public class PubliclySupervisedDateListViewController {
    @FXML
    private ComboBox<String> estlevelCombo;
    private static final List<String>LevelDate = new ArrayList<>();
    static {
        LevelDate.add("优");
        LevelDate.add("良");
        LevelDate.add("轻度污染");
        LevelDate.add("中度污染");
        LevelDate.add("重度污染");
        LevelDate.add("严重污染");
    }

    @FXML
    private ComboBox<String> provinceCombo;  // 省份下拉框
    @FXML
    private ComboBox<String> cityCombo;      // 城市下拉框
    // 全国省份、城市
    private static final Map<String, List<String>>REGION_DATA = new HashMap<>();

    static {
        // 江苏省
        List<String> jiangsuCities = Arrays.asList(
                "南京市", "无锡市", "徐州市", "常州市", "苏州市",
                "南通市", "连云港市", "淮安市", "盐城市", "扬州市",
                "镇江市", "泰州市", "宿迁市"
        );
        REGION_DATA.put("江苏省", jiangsuCities);

        // 浙江省
        List<String> zhejiangCities = Arrays.asList(
                "杭州市", "宁波市", "温州市", "嘉兴市", "湖州市",
                "绍兴市", "金华市", "衢州市", "舟山市", "台州市", "丽水市"
        );
        REGION_DATA.put("浙江省", zhejiangCities);

        // 广东省
        List<String> guangdongCities = Arrays.asList(
                "广州市", "深圳市", "珠海市", "汕头市", "佛山市",
                "韶关市", "湛江市", "肇庆市", "江门市", "茂名市",
                "惠州市", "梅州市", "汕尾市", "河源市", "阳江市",
                "清远市", "东莞市", "中山市", "潮州市", "揭阳市", "云浮市"
        );
        REGION_DATA.put("广东省", guangdongCities);

        // 四川省
        List<String> sichuanCities = Arrays.asList(
                "成都市", "自贡市", "攀枝花市", "泸州市", "德阳市",
                "绵阳市", "广元市", "遂宁市", "内江市", "乐山市",
                "南充市", "眉山市", "宜宾市", "广安市", "达州市",
                "雅安市", "巴中市", "资阳市", "阿坝藏族羌族自治州",
                "甘孜藏族自治州", "凉山彝族自治州"
        );
        REGION_DATA.put("四川省", sichuanCities);

        // 辽宁省
        List<String> liaoningCities = Arrays.asList(
                "沈阳市", "大连市", "鞍山市", "抚顺市", "本溪市",
                "丹东市", "锦州市", "营口市", "阜新市", "辽阳市",
                "盘锦市", "铁岭市", "朝阳市", "葫芦岛市"
        );
        REGION_DATA.put("辽宁省", liaoningCities);

        // 吉林省
        List<String> jilinCities = Arrays.asList(
                "长春市", "吉林市", "四平市", "辽源市", "通化市",
                "白山市", "松原市", "白城市", "延边朝鲜族自治州"
        );
        REGION_DATA.put("吉林省", jilinCities);

        // 黑龙江省
        List<String> heilongjiangCities = Arrays.asList(
                "哈尔滨市", "齐齐哈尔市", "鸡西市", "鹤岗市", "双鸭山市",
                "大庆市", "伊春市", "佳木斯市", "七台河市", "牡丹江市",
                "黑河市", "绥化市", "大兴安岭地区"
        );
        REGION_DATA.put("黑龙江省", heilongjiangCities);

        // 山东省
        List<String> shandongCities = Arrays.asList(
                "济南市", "青岛市", "淄博市", "枣庄市", "东营市",
                "烟台市", "潍坊市", "济宁市", "泰安市", "威海市",
                "日照市", "临沂市", "德州市", "聊城市", "滨州市", "菏泽市"
        );
        REGION_DATA.put("山东省", shandongCities);

        // 山西省
        List<String> shanxiCities = Arrays.asList(
                "太原市", "大同市", "阳泉市", "长治市", "晋城市",
                "朔州市", "晋中市", "运城市", "忻州市", "临汾市", "吕梁市"
        );
        REGION_DATA.put("山西省", shanxiCities);

        // 河北省
        List<String> hebeiCities = Arrays.asList(
                "石家庄市", "唐山市", "秦皇岛市", "邯郸市", "邢台市",
                "保定市", "张家口市", "承德市", "沧州市", "廊坊市", "衡水市"
        );
        REGION_DATA.put("河北省", hebeiCities);

        // 湖南省
        List<String> hunanCities = Arrays.asList(
                "长沙市", "株洲市", "湘潭市", "衡阳市", "邵阳市",
                "岳阳市", "常德市", "张家界市", "益阳市", "郴州市",
                "永州市", "怀化市", "娄底市", "湘西土家族苗族自治州"
        );
        REGION_DATA.put("湖南省", hunanCities);

        // 湖北省
        List<String> hubeiCities = Arrays.asList(
                "武汉市", "黄石市", "十堰市", "宜昌市", "襄阳市",
                "鄂州市", "荆门市", "孝感市", "荆州市", "黄冈市",
                "咸宁市", "随州市", "恩施土家族苗族自治州", "仙桃市",
                "潜江市", "天门市", "神农架林区"
        );
        REGION_DATA.put("湖北省", hubeiCities);

        // 安徽省
        List<String> anhuiCities = Arrays.asList(
                "合肥市", "芜湖市", "蚌埠市", "淮南市", "马鞍山市",
                "淮北市", "铜陵市", "安庆市", "黄山市", "滁州市",
                "阜阳市", "宿州市", "六安市", "亳州市", "池州市", "宣城市"
        );
        REGION_DATA.put("安徽省", anhuiCities);

        // 福建省
        List<String> fujianCities = Arrays.asList(
                "福州市", "厦门市", "莆田市", "三明市", "泉州市",
                "漳州市", "南平市", "龙岩市", "宁德市"
        );
        REGION_DATA.put("福建省", fujianCities);

        // 江西省
        List<String> jiangxiCities = Arrays.asList(
                "南昌市", "景德镇市", "萍乡市", "九江市", "新余市",
                "鹰潭市", "赣州市", "吉安市", "宜春市", "抚州市", "上饶市"
        );
        REGION_DATA.put("江西省", jiangxiCities);

        // 河南省
        List<String> henanCities = Arrays.asList(
                "郑州市", "开封市", "洛阳市", "平顶山市", "安阳市",
                "鹤壁市", "新乡市", "焦作市", "濮阳市", "许昌市",
                "漯河市", "三门峡市", "南阳市", "商丘市", "信阳市", "周口市", "驻马店市", "济源市"
        );
        REGION_DATA.put("河南省", henanCities);

        // 其他省份...
    }

    @FXML
    public void initialize() {
        // 初始化省份数据
        List<String> provinces = new ArrayList<>(REGION_DATA.keySet());
        provinceCombo.setItems(FXCollections.observableList(provinces));

        // 初始状态：城市下拉框置空
        cityCombo.setItems(FXCollections.emptyObservableList());

        ObservableList<String> estlevelList = FXCollections.observableArrayList(LevelDate);
        estlevelCombo.setItems(estlevelList);

        // 绑定查询按钮事件
        queryButton.setOnAction(event -> queryByProvinceAndCity());

        tableView.setItems(tableList);

        colFeedbackerName.setCellValueFactory(new PropertyValueFactory<>("feedbackerName"));
        colLocProvince.setCellValueFactory(new PropertyValueFactory<>("locProvince"));
        colLocCity.setCellValueFactory(new PropertyValueFactory<>("locCity"));
        colEstPollutionLevel.setCellValueFactory(new PropertyValueFactory<>("estPollutionLevel"));
        colFeedbackDate.setCellValueFactory(new PropertyValueFactory<>("feedbackDate"));

        firstMap = FileUtils.readMapObject("FeedbackData.txt");
        tableList.addAll(firstMap.values());
        colLocCity.setCellFactory(TextFieldTableCell.forTableColumn());
        colLocCity.setOnEditCommit(event->{
            FeedbackData c = event.getRowValue();
            String newLocCity = event.getNewValue();
            c.setLocCity(newLocCity);
            firstMap.put(c.getLocCity(),c);
            FileUtils.writeMapObject("FeedbackData.txt",firstMap);
        });

        // 初始化原始数据列表
        originalData = FXCollections.observableArrayList();
        originalData.addAll(tableList);

        tableView.setItems(tableList);
        //动态添加按钮列
        colDetail.setCellFactory(cols->new TableCell<>(){
            private Button btn = new Button("详情");
            {
                btn.setOnAction(e->{
                    FeedbackData testData = getTableView().getItems().get(getIndex());
                    System.out.println("点击了详情：" + testData.getFeedbackerName() + "可以弹出窗口进行其他操作");
                    Stage stage = new Stage();
                    FXMLLoader fxmlLoader = new FXMLLoader();
                    URL url = getClass().getResource("../view/PubliclySupervisedDateDetailsView.fxml");
                    fxmlLoader.setLocation(url);
                    Parent root = null;
                    try {
                        root = fxmlLoader.load();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                    Scene scene = new Scene(root);
                    stage.setScene(scene);
                    stage.showAndWait();
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty?null:btn);
            }
        });
        //动态添加按钮列
        colAssign.setCellFactory(cols->new TableCell<>() {
            private Button btn = new Button("指派");

            {
                btn.setOnAction(e -> {
                    FeedbackData testData = getTableView().getItems().get(getIndex());
                    System.out.println("点击了指派：" + testData.getFeedbackerName() + "可以弹出窗口进行其他操作");
                    Stage stage = new Stage();
                    FXMLLoader fxmlLoader = new FXMLLoader();
                    URL url = getClass().getResource("../view/AssignGridWorkersView.fxml");
                    fxmlLoader.setLocation(url);
                    Parent root = null;
                    try {
                        root = fxmlLoader.load();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                    Scene scene = new Scene(root);
                    stage.setScene(scene);
                    stage.showAndWait();
                });
            }
            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty?null:btn);
            }
        });
        //绑定清除按钮事件
        clear.setOnAction(event -> clearSelection());
    }

    // 事件处理方法：省份选择变化时，加载对应城市数据
    @FXML
    private void onProvinceChanged() {
        String selectedProvince = provinceCombo.getValue();
        if (selectedProvince == null) return; // 未选择时跳过

        List<String> cities = REGION_DATA.get(selectedProvince);
        if (cities != null) {
            ObservableList<String> cityList = FXCollections.observableArrayList(cities);
            cityCombo.setItems(cityList);    // 更新城市下拉框
            cityCombo.setValue(null);        // 清空已选城市
        } else {
            cityCombo.setItems(FXCollections.emptyObservableList());
        }
    }

    @FXML
    private void clearSelection() {
        // 清空省份选择
        provinceCombo.setValue(null);

        // 清空城市选择并重置城市下拉框
        cityCombo.setItems(FXCollections.emptyObservableList());

        // 清空预估等级选择
        estlevelCombo.setValue(null);

        // 清空日期选择
        if (datePicker != null) {
            datePicker.setValue(null);
        }
    }

    @FXML
    private void queryByProvinceAndCity() {
        String selectedProvince = provinceCombo.getValue();
        String selectedCity = cityCombo.getValue();

        // 清空当前列表，准备显示查询结果
        tableList.clear();

        // 如果未选择省份和城市，显示所有数据
        if (selectedProvince == null && selectedCity == null) {
            tableList.addAll(originalData);
            return;
        }

        // 按条件过滤数据
        for (FeedbackData data : originalData) {
            boolean provinceMatch = selectedProvince == null || data.getLocProvince().equals(selectedProvince);
            boolean cityMatch = selectedCity == null || data.getLocCity().equals(selectedCity);

            if (provinceMatch && cityMatch) {
                tableList.add(data);
            }
        }

        // 如果没有找到匹配的数据，显示提示信息
        if (tableList.isEmpty()) {
            showAlert("查询结果", "没有找到符合条件的记录。");
        }
    }

    /**
     * 显示提示对话框
     */
    private void showAlert(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    @FXML
    private TableView<FeedbackData> tableView;
    @FXML
    private TableColumn<FeedbackData,String> colFeedbackerName,colLocProvince,colLocCity,colEstPollutionLevel,colFeedbackDate;
    @FXML
    private TableColumn<FeedbackData,Void> colDetail;
    @FXML
    private TableColumn<FeedbackData,Void> colAssign;
    private ObservableList<FeedbackData> tableList = FXCollections.observableArrayList();

    @FXML
    private Button clear;
    @FXML
    private DatePicker datePicker;

    @FXML
    private Button queryButton; // 查询按钮

    private ObservableList<FeedbackData> originalData; // 存储原始数据，用于重置查询

    private Map firstMap = new HashMap();
}
